import 'dart:convert';

import 'package:client/common/fun.dart';
import 'package:flutter/material.dart';
import 'package:client/common/my_http.dart';
import 'package:client/view/reg.dart';
import 'package:flutter/services.dart';

class LoginRoute extends StatelessWidget {
  LoginRoute({super.key});

  final nameController = TextEditingController();
  final pwdController = TextEditingController();

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("登录"),
      ),
      body: _buildBody(context),
    );
  }

  _doLogin() async {
    var name = nameController.text;
    var pwd = pwdController.text;
    if (name == "") {
      Fun.dialog("错误", "账户不能为空");
      return;
    }
    if (pwd == "") {
      Fun.dialog("错误", "密码不能为空");
      return;
    }
    var data = {'name': name, 'pwd': pwd};

    await MyHttp.login(data);
  }

  _buildBody(context) {
    var loginView = Column(
      children: [
        RawKeyboardListener(
          focusNode: FocusNode(),
          onKey: (event) {
            if (event.runtimeType == RawKeyDownEvent &&
                (event.physicalKey == PhysicalKeyboardKey.enter ||
                    event.physicalKey == PhysicalKeyboardKey.numpadEnter)) {
              _doLogin();
            }
          },
          child: Column(children: <Widget>[
            TextField(
              autofocus: true,
              controller: nameController,
              decoration: const InputDecoration(
                  labelText: "用户名",
                  hintText: "用户名或邮箱",
                  prefixIcon: Icon(Icons.person)),
            ),
            TextField(
              autofocus: true,
              obscureText: true,
              controller: pwdController,
              decoration: const InputDecoration(
                  labelText: "密码",
                  hintText: "密码",
                  prefixIcon: Icon(Icons.password)),
            ),
          ]),
        ),
        Container(
            padding: EdgeInsets.all(30),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(
                    onPressed: () {
                      Navigator.push(context,
                          MaterialPageRoute(builder: (context) {
                        return const RegRoute();
                      }));
                    },
                    child: const Text("注册")),
                TextButton(
                  onPressed: _doLogin,
                  child: const Text("登录"),
                )
              ],
            ))
      ],
    );
    return loginView;
  }
}
